package org.wannatrak.android.activity;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.*;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.R;
import org.wannatrak.android.entity.TrackHistory;
import org.wannatrak.android.exceptions.HttpException;
import org.wannatrak.android.executions.ProjectService;
import org.wannatrak.android.formatter.TimeFormatter;
import org.wannatrak.android.helper.DateHelper;
import org.wannatrak.android.helper.DialogHelper;
import org.wannatrak.android.helper.UIHelper;
import org.wannatrak.android.intf.ClickAction;
import org.wannatrak.android.intf.DialogAction;
import org.wannatrak.android.intf.ItemClickAction;
import org.wannatrak.android.service.WannatrakGPSService;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-12-05 04:56:47 +0000 (Mon, 05 Dec 2011) $
 * @Time: 21:47
 * @Version: $Revision: 34 $
 * @Id: $Id: StartTrackActivity.java 34 2011-12-05 04:56:47Z maxtulupov@gmail.com $
 */
public class StartTrackActivity extends AbstractContextMenuActivity {

    /**
     * thread for executing async login
     */
    private Thread t;

    /**
     * dialog that shows async execution
     */
    private Dialog dialog;

    private String trackId;

    private boolean fromHistory;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_track);
        init();
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        return super.onRetainNonConfigurationInstance();
    }

    private void init() {
        initButtonEnabled();
        DialogHelper.setTimeDialogToTextView(this, (TextView) findViewById(R.id.trackInterval), new DialogHelper.OnTimeSetListener() {
            public void onSet(TimePicker timePicker, int hours, int minutes) {
                Date date = DateHelper.getDate(1, 1, 1, hours, minutes);
                ((TextView) findViewById(R.id.trackInterval))
                        .setText(ApplicationContext.getFormatter(TimeFormatter.class).format(date));
            }
        });

        DialogHelper.setTimeDialogToTextView(this, (TextView) findViewById(R.id.saveInterval), new DialogHelper.OnTimeSetListener() {
            public void onSet(TimePicker timePicker, int hours, int minutes) {
                Date date = DateHelper.getDate(1, 1, 1, hours, minutes);
                ((TextView) findViewById(R.id.saveInterval))
                        .setText(ApplicationContext.getFormatter(TimeFormatter.class).format(date));
            }
        });

        ((TextView) findViewById(R.id.saveInterval)).setText("00:01");
        ((TextView) findViewById(R.id.trackInterval)).setText("00:05");
        ((TextView) findViewById(R.id.trackName)).addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (i != 0) {
                    fromHistory = false;
                }
            }

            public void afterTextChanged(Editable editable) {
            }
        });
        UIHelper.setActionToView(findViewById(R.id.okButton), new StartTrackAction());

        UIHelper.setActionToView(findViewById(R.id.fromHistoryButton), new ClickAction() {
            public boolean actionPerformed(View view) {
                Dialog dialog = UIHelper.createAlertDialog(StartTrackActivity.this,
                        R.string.track_history, R.layout.history_dialog_view, false, null);
                dialog.show();
                initDialog(dialog);
                return true;
            }
        });
    }

    private boolean validateStartTrackInput() {
        String s = ((TextView) findViewById(R.id.trackName)).getText().toString();
        if (s == null || "".equals(s.trim())) {
            UIHelper.createAlertDialog(this, R.string.err_track_name_empty, true, (DialogAction[]) null).show();
            return false;
        }
        String regex = getString(R.string.track_name_regexp);
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(s);
        if (!matcher.matches()) {
            UIHelper.createAlertDialog(this, R.string.err_track_name, true, (DialogAction[]) null).show();
            return false;
        }
        s = ((TextView) findViewById(R.id.trackInterval)).getText().toString();
        if (s == null || "".equals(s.trim()) || "00:00".equals(s.trim())) {
            UIHelper.createAlertDialog(this, R.string.err_track_interval_empty, true, (DialogAction[]) null).show();
            return false;
        }

        return true;
    }

    private class StartTrackAction implements ClickAction {

        public boolean actionPerformed(View view) {
            if (!validateStartTrackInput()) {
                return true;
            }
            dialog = DialogHelper.createProgressDialog(StartTrackActivity.this);
            final DialogHandler handler = new DialogHandler(dialog, StartTrackActivity.this);
            dialog.show();
            Runnable r = new Runnable() {
                public void run() {
                    Looper.prepare();
                    String trackName = ((TextView) findViewById(R.id.trackName)).getText().toString();
                    String trackInterval = ((TextView) findViewById(R.id.trackInterval)).getText().toString();
                    String saveInterval = ((TextView) findViewById(R.id.saveInterval)).getText().toString();
                    ApplicationContext.getSettingService().saveSetting("trackName", trackName);
                    ApplicationContext.getSettingService().saveSetting("trackInterval", trackInterval);
                    ApplicationContext.getSettingService().saveSetting("saveInterval", saveInterval);

                    try {
//                        if (ApplicationContext.getWannatrakService().login()) {
                            if (fromHistory) {
                                ApplicationContext.getWannatrakService().continueTrack(
                                        trackName, trackInterval, saveInterval, trackId);
                            } else {
                                trackId = ApplicationContext.getWannatrakService()
                                        .createTrack(trackName, trackInterval, saveInterval);
                            }
                            ApplicationContext.getSettingService().saveSetting("isTracking", "true");
                            ApplicationContext.getSettingService().saveSetting("currentTrack", trackName);
                            ApplicationContext.getTrackHistoryService().putInHistory(
                                    trackName, trackInterval, saveInterval, trackId);
                            restartService();
                            finish();
//                        }
                    } catch (HttpException e) {
                        handler.sendMessage(handler.obtainMessage(-1234, e.getMessage()));
                    } finally {
                        dialog.dismiss();
                    }
                }
            };
            t = new Thread(r);
            t.start();
            return true;
        }
    }

    /**
     * stop and start service for sending coordinates with new Interval
     */
    private void restartService() {
        WannatrakGPSService service = ApplicationContext.getWannatrakGPSService();
        service.stopTracking();
        if (service.startTracking()) {
            Log.e(getClass().getSimpleName(), " try to start service");
            stopService(new Intent(this, ProjectService.class));
            startService(new Intent(this, ProjectService.class));
        }
    }

    private void initButtonEnabled() {
        findViewById(R.id.fromHistoryButton).setEnabled(!ApplicationContext.getTrackHistoryService().isHistoryEmpty());
    }

    private void initDialog(final Dialog dialog) {
        ListView listView = (ListView) dialog.findViewById(R.id.trackHistoryList);
        final Cursor c = getContentResolver().query(TrackHistory.CONTENT_URI, null, null, null, TrackHistory.NAME);
        startManagingCursor(c);
        CursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.dropdown_item, c,
                new String[]{TrackHistory.NAME}, new int[]{android.R.id.text1});
        listView.setAdapter(adapter);
        UIHelper.setActionToView(listView, new ItemClickAction() {
            public boolean onItemSelect(AdapterView parent, View view, int position, long id) {
                if (c.moveToPosition(position)) {
                    ((TextView) findViewById(R.id.trackName)).setText(c.getString(c.getColumnIndex(TrackHistory.NAME)));
                    ((TextView) findViewById(R.id.trackInterval)).setText(c.getString(c.getColumnIndex(TrackHistory.SEND_INTERVAL)));
                    ((TextView) findViewById(R.id.saveInterval)).setText(c.getString(c.getColumnIndex(TrackHistory.SAVE_INTERVAL)));
                    trackId = c.getString(c.getColumnIndex(TrackHistory.TRACK_ID));
                    fromHistory = true;
                }
                dialog.dismiss();
                return true;
            }

            public void onNothingSelected(AdapterView parent) {
            }
        }, UIHelper.ON_CLICK);
    }
}
